<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_one">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="计划开始时间" prop="startTime">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm"
            placeholder="请选择"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="执行间隔（秒）" prop="interval">
          <el-input
            v-model="formData.interval"
            clearable
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate } from '@/api/equipmentManage/equipmentMaintain/maintainPlan'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    selectionsAll: {}
  },
  data() {
    const validate_interval = (rule, value, callback) => {
      if (!value) {
        callback(new Error('执行间隔不能为空'))
      } else {
        const reg = /^[1-9]\d*$/
        if (!reg.test(value)) {
          callback(new Error('你再乱输？！'))
        } else {
          callback()
        }
      }
    }
    return {
      formData: {
        startTime: '',
        interval: 2
      },
      loading: false,
      rules: {
        startTime: [
          { required: true, message: '计划开始时间不能为空', trigger: 'change' }
        ],
        interval: [
          { required: true, validator: validate_interval, trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
  },
  methods: {
    // 提交
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          for (let i = 0; i < this.selectionsAll.length; i++) {
            setTimeout(() => {
              const item = this.selectionsAll[i]
              item.startTime = this.formData.startTime

              addOrUpdate(item).then(res => {
                this.$message({
                  message: '计划：' + item.code + ' ' + res.msg,
                  type: 'success'
                })
              })
              if (i == this.selectionsAll.length - 1) {
                setTimeout(() => {
                  this.$layer.close(this.layerid) // 关闭弹框
                  this.$parent.getList()
                  this.loading = false
                }, 1000)
              }
            }, Number(this.formData.interval) * 1000 * i)
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.expand_radio{
  padding-top: 20px;
}
/deep/ .el-form-item__label{
  width: 150px !important;
}
</style>
